package org.example.exam.compenet;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.example.ExamApp;
import org.example.exam.Paper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Stream;

/**
 * 试卷加载组件
 *
 * @author bobo
 * @since 2024/4/27
 */
@Component
public class PaperLoad {
	public static List<Paper> papers = new ArrayList<>();
	private final ObjectMapper mapper;

	@Autowired
	public PaperLoad(ObjectMapper mapper) {
		this.mapper = mapper;
	}

	public void loadPapers(String dir) {
		try {
			Path path = Paths.get(Objects.requireNonNull(ExamApp.class.getClassLoader().getResource(dir)).toURI());
			try (Stream<Path> paths = Files.walk(path)) {
				paths
						.filter(Files::isRegularFile)
						.filter(p -> p.toString().endsWith(".json"))
						.forEach(p -> {
							try {
								Paper paper = mapper.readValue(p.toFile(), Paper.class);
								papers.add(paper);
							} catch (IOException e) {
								e.printStackTrace();
							}
						});
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
